/**
 * Created by IntelliJ IDEA.
 * User: dinesh
 * Date: Apr 14, 2012
 * Time: 12:19:54 PM
 * To change this template use File | Settings | File Templates.
 */
/* trim */
	function trimj(strValue){
		var objRegExp = /^(\s*)$/;

	    /*check for all spaces */
	    if(objRegExp.test(strValue)) {
	       strValue = strValue.replace(objRegExp, '');
	       if( strValue.length == 0)
	          return strValue;
	    }

	   /*check for leading & trailing spaces */
	   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
	   if(objRegExp.test(strValue)) {
	       /*remove leading and trailing whitespace characters */
	       strValue = strValue.replace(objRegExp, '$2');
	    }

	  	return strValue;
	}
function trim(s)
{
	return rtrim(ltrim(s));
}

function ltrim(s)
{
	var l=0;
	while(l < s.length && s[l] == ' ')
	{	l++; }
	return s.substring(l, s.length);
}

function rtrim(s)
{
	var r=s.length -1;
	while(r > 0 && s[r] == ' ')
	{	r-=1;	}
	return s.substring(0, r+1);
}

/**
	 * Clears the specified form.
	 *
	 * @param strFormId
	 *            form to be cleared
	 *
	 * @param arrSkipFields (optional)
	 * 			   an array of IDs if fields to be skipped
	 */
	function clearForm(strFormId, arrSkipFields) {

		$("#" + strFormId).each(function() {
			$('input,select,textarea', this).each(function() {

				if (arrSkipFields) {
					for (var i=0; i < arrSkipFields.length; i++) {
						if (this.id === arrSkipFields[i]) {
							// Skip the field
							return;
						}
					}
				}

				clearField(this);

				//If the radio button is type radio the the focus is set to the first field of the group
				if(this.type == 'radio'){
					setDefaultRadButtonFocus(this.name);
				}
			});
		});


	}
/**
	 * Clears an input field.
	 * <p>
	 * Original Source : JQuery Form Plugin. Modified to support hidden fields.
	 *
	 * @param elm
	 * @return
	 */
	function clearField(elm) {

		return $(elm).each(function() {
	        var t = this.type, tag = this.tagName.toLowerCase();
	        if (t == 'text' || t == 'password' || tag == 'textarea' || t=='hidden') {

	        	// If constant attribute is defined, do not clear
	        	// Use this to make hidden fields constant.
	        	if (this.attributes['constant']!=undefined) return;

	            this.value = '';
	        }
	        else if (t == 'checkbox' || t == 'radio') {
	            this.checked = false;
	        }
	        else if (tag == 'select') {
	            this.selectedIndex = 0;
	        }
	    });

	}
function setDefaultRadButtonFocus(strRadName){
		$('input[name="'+strRadName+'"]')[0].checked = true;
	}
function disableForm(strFormId,blnDisableBtns) {
		var form1 = $("#" + strFormId)[0];
		for (var i=0; i <form1.elements.length; i++) {
			var elm = form1.elements[i];
			if (elm!=undefined) {
				if (elm.type=="hidden") continue;	// Skip Hidden Fields
				if(!blnDisableBtns){
				disableElement(elm.id);
			}
		}
	}
}
function disableElement(id) {

		var elm = $("#" + id);
		elm.attr("disabled","disabled");

		//disable if any datepickers/calendar attached.
		if(elm.hasClass("calendar")){
			elm.datepicker('disable');
		}
		return true;
	}

function enableForm(strFormId) {

		var form = $("#" + strFormId)[0];

		for (var i=0; i < form.elements.length; i++) {
			var elm = form.elements[i];
			if (elm!=undefined) {
				enableElement(elm.id);
			}
		}

	}
function enableElement(id, blnForce) {
		var elm = $("#" + id);

		if (blnForce) {
			// Forcefully enable. Do not check for disableAlways or privileges.
			elm.removeAttr("disabled");
			return;
		}

		// Check for privielges attribute
		if (elm.attr("privilege")!=undefined) {

			var strPrivis = elm.attr("privilege");

			
			var arrPrivis = $.trim(strPrivis).split(" ");

		}

		// Dont enable if it has disableAlways class
		if (elm.hasClass("disableAlways")) {
			// Do not enable
			return false;
		}

		elm.removeAttr("disabled");

		//enable if any datepickers/calendar attached.
		if(elm.hasClass("calendar")){
			elm.datepicker('enable');
		}

		return true;
}
/**
	 * Default button handler for events.
	 *
	 * @param strEvent
	 * @return
	 */
	function handleDefaultButtons(strEvent) {
		switch (strEvent){
			case "load" :
				enableElement("btnAdd");
				disableElement("btnEdit");
				disableElement("btnDelete");
				disableElement("btnSave");
				break;
			case "save" :
				disableElement("btnSave");
				break;
			case "delete" :
				disableElement("btnDelete");
				disableElement("btnSave");
				break;
			case "edit" :
				enableElement("btnSave");
				disableElement("btnDelete");
				disableElement("btnEdit");
				break;
			case "add" :
				enableElement("btnSave");
				break;
			case "gridclick" :
				enableElement("btnAdd");
				enableElement("btnEdit");
				enableElement("btnDelete");
				disableElement("btnSave");
				break;
			case "init" :
				disableElement("btnEdit");
				disableElement("btnDelete");
				disableElement("btnSave");
				break;
		}
	}



/* Set values to a control  */
	function setField(strControlID, strControlValue){

		var objControl = getFieldByID(strControlID) ;

		if (objControl==null) {
			objControl = getFieldByName(strControlID)[0];
		}

		var strType = getFieldType(objControl);

		switch (strType){
			case "TEXT" : objControl.value = strControlValue ; break ;
			case "PASSWORD" : objControl.value = strControlValue ; break ;
			case "HIDDEN" : objControl.value = strControlValue ; break ;
			case "TEXTAREA" : objControl.value = strControlValue ; break ;
			case "CHECKBOX" :
				objControl = getFieldByName(strControlID);
				var intLength = objControl.length ;
				if (strControlValue != true && strControlValue != false){
					var arrConValue = strControlValue.split(",");
					var intArrLength = arrConValue.length ;
					if (strControlValue == ""){
						for (var i = 0 ; i < intLength ; i++){
							objControl[i].checked = false;
						}
					}

					for (var x = 0; x < intArrLength ; x++){
						for (var i = 0 ; i < intLength ; i++){
							if (objControl[i].value == arrConValue[x]){
								if (!objControl[i].disabled){
									objControl[i].checked = true;
								}
								break;
							}
						}
					}
				}else{
					for (var i = 0 ; i < intLength ; i++){
						if (!objControl[i].disabled){
							objControl[i].checked = strControlValue;
						}

					}
				}
				break;

			case "RADIO" :
				objControl = getFieldByName(strControlID);
				var intLengrh = objControl.length ;
				if (strControlValue == ""){
					for (var i = 0 ; i < intLengrh ; i++){
						objControl[i].checked = false;
					}
				}
				for (var i = 0 ; i < intLengrh ; i++){
					if (objControl[i].value == strControlValue){
						objControl[i].checked = true;
						break;
					}
				}
				break;

			case "SELECT-ONE" :
				var intLengrh = objControl.length ;
				for (var i = 0 ; i < intLengrh ; i++){
					if (objControl.options[i].value == strControlValue){
						objControl.options[i].selected = true;
						break;
					}
				}
				break;

			case "SELECT-MULTIPLE" :
				var intLengrh = objControl.length ;
				var arrConValue = strControlValue.split(",");
				var intArrLength = arrConValue.length ;
				if (strControlValue == ""){
					for (var i = 0 ; i < intLengrh ; i++){
						objControl.options[i].selected = false;
					}
				}
				for (var x = 0; x < intArrLength ; x++){
					for (var i = 0 ; i < intLengrh ; i++){
						if (objControl.options[i].value == arrConValue[x]){
							objControl.options[i].selected = true;
							break;
						}
					}
				}
				break;
		}
	}
/* Get the control as Object */
	function getFieldByID(strControlID){return document.getElementById(strControlID);}
	function getFieldByName(strControlName){return document.getElementsByName(strControlName);}

	/* Get the Field Type */
	function getFieldType(objControl){return objControl.type.toUpperCase();}

/**
	 * Strips off currency commas from all currency validated fields in the
	 * specified form.
	 *
	 * @param strFormId
	 * @return
	 */
	function stripOffCurrencyFields(strFormId) {
		$("#" + strFormId + " input[validate*='currency']").each(function (i) {
			setField(this.id, stripCurrencySeperators( getValue(this.id) ) );
		});
	}

/**
	 * Strips off currency seperator commas from the given value, and
	 */
	function stripCurrencySeperators(strValue) {
		return strValue.replace(/\,/g,'');
	}
/**
	 * Serializes a given form to Query String format.
	 *
	 * @param strFormId
	 *            form to be serialized
	 */
	function serializeForm(strFormId) {

		var form = $("#" + strFormId);

		// Strip off commas
		stripOffCurrencyFields(strFormId);

		// Use standard jQuery Serialization
		var strSerialized = form.serialize();

		// Standard jQuery Serialization will avoid unchecked checkboxes.
		// We have to manually attach blank fields for such checkboxes.

		$(":checkbox:not(:checked)", form).each(function () {
			// Append "&<field_name>=" to query string
			strSerialized += ("&" + encodeURIComponent(this.name) + "=");
		});

		return strSerialized;
	}

/**
	 * Performs an Ajax Post operation, using jQuery.
	 *

	 *
	 * @param action
	 *            action to post, including context path but without .action
	 *            suffix (ex. /aeris-web/secure/showUser).
	 *
	 * @param method
	 *            method to be invoked in action. If left blank (""), it will
	 *            invoke the action without any method (will usually fallback to
	 *            execute method).
	 *
	 * @param params
	 *            request parameters (query string format)
	 * @param callback
	 *            callback function to call when response is obtained
	 * @param contentType
	 *            content type
	 * @param returnType
	 *            return data type (xml, html, script, json, text) - see jQuery
	 *            API Doc (dataType of ajax)
	 * @param async
	 *            whether the posting should happen asynchronously. Default is true.
	 * @param additionalURLParams
	 * 			  additional URL parameters. Should follow the form '?key=value'
	 * @param background (boolean) whether this is a background call (no progress is displayed)
	 */
	function ajaxPost(strURL, params, callback, contentType, returnType, async, additionalURLParams, background) {

		// Assign default value to type if its not specified
		if (!contentType) contentType = "application/x-www-form-urlencoded";

		// Assign default value to async if its not specified
		if (async===undefined) async = true;

		if (background === undefined) background = false;

		// Check Ajax Flag, and show Processing Please Wait if
		// a request is still processing
		// if (! topProcessCheck()) {
		// return false;
		// }

		// Note on above : No need of a process check anymore as the response for each request
		// is handled by its own callback. Multiple concurrent ajax calls are possible.


		//var strURL = buildActionURL(action, method);

		if (additionalURLParams) {
			strURL += additionalURLParams;
		}




		 var start = new Date().getTime();

		 $.ajax({

			 type: "POST",
			 url: strURL,
			 data: params,
			 cache: false,
			 contentType : contentType,
			 dataType : returnType,
			 processData: false,
			 async : async,
			 beforeSend: function() {

			 	if (! background) {


			 	}

			 	return true;
		 	 },
			 success: function(data) {




		 		// AJAX Request Success



			 	// Invoke user callback
			 	callback(data);
		 	 },
		 	 error : function (xhr, textStatus, errorThrown) {

		 			 		

		 		// AJAX Request Failed



		 		if (textStatus==="timeout") {
		 			// Ajax Time Out

		 		}
		 		else {
		 			// Generic Error Message

		 		}

		 	}

		 });
	}
/**
	 * Evaluates a JSON Expression in a String to build a JavaScript object.
	 *
	 * @param strJson
	 *            JSON Expression String
	 * @return JavaScript object
	 */
	function toObject(strJson) {
		return eval( "(" + strJson + ")" );
	}